<template>
  <div class="container-box">
    <!--筛选表单-->
    <div class="tag-form">
      <el-form ref="form" label-width="80px" :inline="true" size="small">
        <el-form-item>
          <el-input v-model="query.title" placeholder="请输入面试标题" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.subject.subjectId" placeholder="请选择学科">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.subjectName"
              :value="item.subjectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="query.name" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.isTop" placeholder="是否置顶">
            <el-option
              v-for="(item, index) in hotValue"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.isCollect" placeholder="是否关注">
            <el-option
              v-for="(item, index) in collevtValue"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="seacherSubject"
          >搜索</el-button>
          <el-button
            icon="el-icon-refresh"
            @click="resetSeacher"
          >重置</el-button>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="space-between" class="tool-bar">
        <div>
          <el-button
            icon="el-icon-plus"
            type="primary"
            size="small"
            plain
            @click="(isShow = true), (type = 'add')"
          >创建</el-button>
        </div>
      </el-row>
    </div>
    <!--操作区域-->

    <!--表单区域-->

    <div class="table-box">
      <el-table :data="list" border stripe>
        <el-table-column type="index" label="序号" />
        <el-table-column prop="title" label="面试题标题" />
        <el-table-column prop="description" label="面试题描述" />
        <el-table-column prop="subject.sujectId" label="所属学科">
          <template slot-scope="{ row }">
            <span class="span_button">{{ row.subject.subjectName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="是否置顶">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.isTop"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column prop="isCollect" label="是否关注">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.isCollect"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column prop="image" label="面试题封面">
          <template slot-scope="{ row }">
            <img
              :src="
                row.image.includes('http')
                  ? row.image
                  : `http://124.223.14.236:7005/` + row.image
              "
              alt=""
              class="image"
            >
          </template>
        </el-table-column>
        <el-table-column prop="sciFactor" label="SCI影响因子">
          <template slot-scope="{ row }">
            <span class="span_button">{{ row.sciFactor }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="创建者">
          <template slot-scope="{ row }">
            <span class="span_button">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />

        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-edit"
              circle
              class="editbtn"
              @click="editSubjectItem(row.id)"
            />
            <el-popconfirm title="确定删除吗" @onConfirm="deleteItem(row.id)">
              <el-button
                slot="reference"
                size="small"
                type="danger"
                icon="el-icon-delete"
                circle
              />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页区域-->
    <!-- isShow=true,type='edit' -->
    <div class="page">
      <!-- 三个变量（页码，总数，每页数），两个事件（每页数量切换 ，页码切换） -->
      <el-pagination
        :current-page.sync="query.page"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="query.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @current-change="currentChange"
        @size-change="limitChange"
      >
        :pager-count="7">
      </el-pagination>
    </div>
    <el-dialog
      :title="type === 'edit' ? '修改面试题' : '添加面试题'"
      :visible.sync="isShow"
      width="45%"
      @close="onClose"
    >
      <el-form
        ref="form"
        label-width="120px"
        size="normal"
        :model="formData"
        :rules="rules"
      >
        <el-row type="flex">
          <el-form-item label="面试题标题" prop="title">
            <el-input v-model="formData.title" style="width: 240px" />
          </el-form-item>
          <el-form-item label="面试题描述" prop="description">
            <el-input v-model="formData.description" style="width: 240px" />
          </el-form-item>
        </el-row>

        <el-row type="flex">
          <el-form-item label="创建者" prop="name">
            <el-input v-model="formData.name" style="width: 240px" />
          </el-form-item>
          <el-form-item label="所属学科" prop="subject.subjectId">
            <el-select
              v-model="formData.subject.subjectId"
              placeholder="请选择学科"
              style="width: 240px"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.subjectId"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row type="flex">
          <el-form-item label="创建日期" prop="createTime">
            <el-date-picker
              v-model="formData.createTime"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              @change="selectTime"
            />
          </el-form-item>

          <el-form-item label="面试题内容" prop="content">
            <el-input
              v-model="formData.content"
              style="width: 240px"
              type="textarea"
            />
          </el-form-item>
        </el-row>
        <el-row type="flex">
          <el-form-item label="影响因子" prop="sciFactor">
            <el-input-number
              v-model="formData.sciFactor"
              :min="1"
              :max="55"
              label="描述文字"
            />
          </el-form-item>
          <el-form-item label="是否收藏" prop="isCollect" label-width="180px">
            <el-switch
              v-model="formData.isCollect"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="是否置顶" prop="isTop">
            <el-switch
              v-model="formData.isTop"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-row>

        <!-- 图片上传 -->
        <el-form-item label="面试题封面" prop="image" class="imagepic">
          <!-- <el-upload
            ref="uploadImage"
            action="#"
            list-type="picture-card"
            :http-request="httpRequest"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload> -->

          <el-upload
            class="avatar-uploader"
            action="#"
            list-type="picture-card"
            :show-file-list="false"
            :http-request="httpRequest"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-row type="flex" justify="center">
          <el-button @click="isShow = false">取消</el-button>
          <el-button
            v-if="type === 'edit'"
            type="primary"
            @click="updateSubject"
          >修改</el-button>
          <el-button v-else type="primary" @click="addSubject">新增</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment'
import { getToken } from '@/utils/auth'
import { getSubjectApi, uploadImage, addSubjectApi, getAllSubjectApi, delSubjectApi, updataSubjectApi, editSubjectApi } from '@/api/subject'
export default {
  data() {
    return {
      headers: { Authorization: `Bearer ` + getToken() },
      dialogVisible: false,
      dialogImageUrl: '',
      type: '',
      isShow: false,
      hotValue: [
        {
          name: '是',
          value: 1
        },
        {
          name: '否',
          value: 0
        }
      ],
      collevtValue: [
        {
          name: '是',
          value: 1
        },
        {
          name: '否',
          value: 0
        }
      ],
      // 时间选择器特有时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      imageUrl: '',
      // 表格数据
      list: [],
      subjectList: [],
      // 查询参数(请求时携带的参数)
      query: {
        title: '',
        subject: { subjectId: '', subjectName: '' },
        name: '',
        isTop: '',
        isCollect: '',
        page: 1,
        limit: 10
      },
      total: 0,
      formData: {
        title: '',
        description: '',
        subject: { subjectId: '', subjectName: '' },
        isTop: 0,
        isCollect: 0,
        sciFactor: 1,
        name: '',
        createTime: '',
        image: '',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能是空的', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能是空的', trigger: 'blur' }
        ],
        subjectId: [
          { required: true, message: '学科不能是空的', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '作者不能是空的', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请选择时间  ', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '封面图不能是空的', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能是空的', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getSubjectList()
    this.getAllSubject()
  },
  methods: {
    // 获取列表渲染
    async getSubjectList() {
      const res = await getSubjectApi(this.query)
      // console.log(res)
      this.list = res.data.data.list
      this.total = res.data.data.total
    },
    // 查
    async seacherSubject() {
      this.getSubjectList()
    },
    // 上传图片
    async httpRequest({ file }) {
      const fd = new FormData()
      fd.append('file', file)
      const res = await uploadImage(fd)
      console.log(res)
      this.formData.image = res.url
      this.imageUrl = 'http://124.223.14.236:7005/' + res.url
      // this.dialogImageUrl = res.url
    },
    // 获取学科
    async getAllSubject() {
      const res = await getAllSubjectApi()
      // console.log(res)
      this.subjectList = res.data.data.subJectArr
    },
    // 新增
    async addSubject() {
      this.formData.subject.subjectName = this.subjectList.find(item => item.subjectId * 1 === this.formData.subject.subjectId * 1).subjectName
      await this.$refs.form.validate()
      await addSubjectApi(this.formData)
      this.$message.success('操作成功')
      this.getSubjectList()
      this.isShow = false
    },
    // 删除
    async deleteItem(id) {
      if (this.query.page > 1 && this.list.length === 1) {
        this.query.page--
      }
      await delSubjectApi({ id })
      this.getSubjectList()
      this.$message.success('操作成功')
    },
    // 回显
    async editSubjectItem(id) {
      this.type = 'edit'
      const res = await editSubjectApi({ id })
      console.log(res)
      this.formData = res.data.data
      this.imageUrl = res.data.data.image.includes('http') ? res.data.data.image : 'http://124.223.14.236:7005/' + res.data.data.image
      this.isShow = true
    },
    // 修改
    async updateSubject() {
      this.formData.subject.subjectName = this.subjectList.find(item => item.subjectId * 1 === this.formData.subject.subjectId * 1).subjectName
      await this.$refs.form.validate()
      await updataSubjectApi(this.formData)
      this.$message.success('操作成功')
      this.getSubjectList()
      this.isShow = false
    },
    // 重置筛选
    resetSeacher() {
      this.query = {
        title: '',
        subject: { subjectId: '', subjectName: '' },
        name: '',
        isTop: '',
        isCollect: '',
        page: 1,
        limit: 10
      }
      this.getSubjectList()
    },
    // 关闭弹窗
    onClose() {
      // console.log(1)
      this.formData = {
        title: '',
        description: '',
        subject: { subjectId: '', subjectName: '' },
        isTop: 0,
        isCollect: 0,
        sciFactor: 1,
        name: '',
        createTime: '',
        image: '',
        content: ''
      }
      this.imageUrl = ''
      this.$refs.form.clearValidate()
    },

    // 时间选择
    selectTime(time) {
      this.formData.createTime = moment(time).format('YYYY-MM-DD')
    },
    // 页码变动
    currentChange(value) {
      // console.log(value)
      this.query.page = value
      this.getSubjectList()
    },
    // 每页数量变动
    limitChange(value) {
      this.query.limit = value
      this.getSubjectList()
    }
  }
}
</script>

<style scoped>
.container-box {
  padding: 30px;
}
.filter-form,
.tool-bar {
  /* border: 1px solid #ddd; */
  padding: 5px 15px 10px;
  margin-bottom: 10px;
}
.tag-form {
  display: flex;
  justify-content: space-between;
}
.image {
  width: 60px;
  height: 36px;
}
::v-deep .el-table td,
.el-table th.is-leaf {
  padding: 10px 0;
  text-align: center;
}
.span_button {
  color: #58acfa;
  background-color: #e8f5f7;
  cursor: pointer;
  display: inline-block;
  padding: 1px 8px;
  border: 1px solid #b5d8f8;
  border-radius: 3px;
}
::v-deep .el-table_1_column_1 .cell {
  padding: 0 !important;
  letter-spacing: 2px;
}
::v-deep .is-leaf {
  text-align: center;
}
::v-deep .el-dialog {
  height: 600px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  line-height: 146px;
  text-align: center;
  border-radius: 5px;
}
.avatar {
  width: 146px;
  height: 146px;
  display: block;
  border-radius: 5px;
}
.editbtn {
  margin-right: 10px;
}
</style>
